<template>
  <el-form-item prop="code" :rules="rules">
    <el-button type="button" class="button-vcode" :loading="isLoading" :disabled="disabled" @click="handleCode">{{btn_text}}</el-button>
    <el-input v-model="code" placeholder="验证码" @input="enterInput"></el-input>
  </el-form-item>
</template>

<script>
import {GetCode} from "@/api/account.js";

export default {
  name: "Code",
  props: {
    username: {type:String,default:""},
    // secode: {type:Number,default:0}
  },
  watch:{
    username: {
      handler(newValue, oldValue) {
        this.disabled = newValue ? false : true;
      }
    }
  },
  data() {
    return {
      isLoading: false,
      code: "",
      disabled: true,
      timer: null,
      btn_text: "获取验证码",// 按钮文本
      rules: [
        {required:true,message:"验证码不能为空",trigger:"blur"},
        {min:6,max:6,message:"请输入6位的验证码",trigger:"change"}
      ]
    }
  },
  methods: {
    enterInput() {
      this.$emit("update:value", this.code);
    },
    handleCode() {
      this.isLoading = true;
      const params = {
        username: this.username,
        module: "register"
      }
      GetCode(params).then((res) => {
        this.$message({
          type: "success",
          message: res.message
        })
        this.isLoading = false;
      }).catch((err) => {
        this.isLoading = false;
      })
      this.countDown();
    },
    countDown() {
      let seconde = 45;
      this.btn_text = `倒计时${seconde}秒`;
      this.disabled = true;
      this.timer = setInterval(() => {
        seconde--;
        this.btn_text = `倒计时${seconde}秒`;
        if(seconde === 0) {
          this.btn_text = "重新获取";
          this.disabled = false;
          clearInterval(this.timer);
        }
      },1000)
    }
  }
}
</script>

<style lang="less" scoped>

</style>